# coding:utf-8
#########################
#   Author : Lion yu    #
#   Date : 2023/08/04   #
#   Id : SM2772         #
#########################
import time
from handle import *
from tbUtils.TbOpenApis import ProjectTaskQuery
from tbUtils.getResp import *
from tbUtils.DataIntoDB import *
from tbUtils.statistics import statisticsData
from tbUtils.statistics2week import statisticsData2Week
from Apis import Tables
from Notice.ddNotice import DDnotices
from distributed import MyZK as MZK


def chief(projectIdList:list, updateMembers:int):
    zkClient = MZK()
    if updateMembers == 1:
        OrgDepartments_DataWrite()
        DepartmentMembers_DataWrite()
    Handle.db_delete(table='project')
    ProjectQuery_DataWrite()
    emptyProjectIdList = []
    for projectId in projectIdList:
        checkRealData = dataInit(projectId)
        if checkRealData == 0:
            # 直接释放锁
            zkClient.release_key(projectId)
            Log.info(f"projectId : {projectId} 没数据, continue掉了")
            emptyProjectIdList.append(projectId)
            continue
        write_startTime = time.time()
        for table in Tables:
            Handle.db_delete(table=table, where=f"projectId = '{projectId}'")
        # 数据写入
        dataWrite(projectId=projectId)
        write_finishTime = time.time()
        Log.info(f"{projectId} 运行结束 耗时 {round(int(write_finishTime-write_startTime)/60, 2)} 分钟")
        # 释放锁
        releaseKey = zkClient.release_key(projectId)
        if releaseKey is False:
            Log.error(f"###################  {projectId} 释放锁失败！  ###################")
            continue
    zkClient.stop()
        
    # 钉钉通知
    ProjectIdListBase = [i for i, j in ProjectConfig.items()]
    # 空数据的projectId过滤掉
    projectIdList = list(set(projectIdList) - set(emptyProjectIdList))
    projectIdList.sort()
    ProjectIdListBase.sort()
    projectLinkInfo = {i:j['NoticeConf'] for i, j in ProjectConfig.items() if len(j['NoticeConf']) > 0}
    isAppoint = False
    if projectIdList != ProjectIdListBase:
        isAppoint = True
        projectIdList = [i for i in projectIdList if i in list(projectLinkInfo.keys())]
        projectLinkInfo = {i:projectLinkInfo[i] for i in projectIdList}
    
    projectLinkMaps = list()
    for i, noticeInfo in projectLinkInfo.items():
        for title, link in noticeInfo.items():
            projectLinkMapsInfo = dict()
            projectLinkMapsInfo['title'] = title
            projectLinkMapsInfo['actionURL'] = link
            projectLinkMaps.append(projectLinkMapsInfo)
    # projectLinkMaps = [{"title": list(j.keys())[0], "actionURL" : list(j.values())[0]} for i, j in projectLinkInfo.items()]
    # projectNames = " \n\n ".join([f"** {list(j.keys())[0]} **" for i, j in projectLinkInfo.items()])
    projectNames = " \n\n ".join([f"** {list(i.values())[0]} **" for i in projectLinkMaps])
    
    # 钉钉通知初始化
    DingTalkNotice = DDnotices()
    try:
        DingTalkNotice.send_message(msg=projectNames, btnsInfo=projectLinkMaps, isAppoint=isAppoint)
        Log.info("钉钉消息发送成功")
    except Exception as e:
        Log.error("钉钉消息发送失败")
    Log.info("All processing programs have been executed this time\n")
    return


def dataWrite(projectId):
    Log.info('task_ext 开始写入')
    ProjectTaskQuery_DataWrite(projectId, 'task_ext')
    Log.info('task_type_info_ext 开始写入')
    ScenarioFieldConfigSearch_DataWrite(projectId, 'task_type_info_ext')
    Log.info('bugs_ext 开始写入')
    ProjectBugQuery_DataWrite(projectId, 'bugs_ext')
    Log.info('bugs_snapshot_ext 开始写入')
    AllTaskActivity_DataWrite(projectId, 'bugs_snapshot_ext')
    Log.info('statistics 开始写入')
    statisticsData_DataWrite(projectId)
    Log.info('statistics2Week 开始写入')
    statistics2Week_DataWrite(projectId)
    
def dataInit(projectId):
    checkEmptyDF = ProjectTaskQuery(projectId=projectId)
    if len(checkEmptyDF['result']) == 0:
        # 无任务的TB项目，过滤掉
        return 0
    
    Log.info(f"projectId:{projectId} data init is startd")
    init_startTime = time.time()
    Handle.db_delete(table="projectId_columns_ext", where=f"projectId = '{projectId}'")
    Handle.db_delete(table="bugSfcId_ext", where=f"projectId = '{projectId}'")
    BugSfcId_DataWrite(projectId, table_name='bugSfcId_ext')
    Log.info(f"projectId : {projectId} 项目自定义字段 与 项目Bug等级sfcId 数据 写入完成")
    
    # 生成task文件
    SimpleResp_ProjectTaskQuery(projectId)
    Log.info(f"projectId : {projectId} Task文件 生成完成")
    # 生成待处理的bug文件
    Bugs_BaseData(projectId)
    # 记录 项目Bug 与 tfsId、reopenID 映射 写入
    ProjectColumns_DataWrite(projectId)
    # 生成bug文件
    SimpleResp_ProjectBugQuery(projectId)
    Log.info(f"projectId : {projectId} Bug文件 生成完成")
    
    # 特殊项目处理
        # 1. 商米安全问题改善
    specialProjectIds = ['64accd09bf9093e620ff5005']
    if projectId in specialProjectIds:
        TaskActivity2SunmiSafeProject(projectId)
        Log.info("special Projects Snapshot is Done！")
    else:
        # 生成bug快照文件
        AllTaskActivity(projectId)
    Log.info(f"projectId : {projectId} Bug快照文件 生成完成")
    # 生成bug月统计文件
    statisticsData(projectId)
    Log.info(f"projectId : {projectId} Bug月统计文件 生成完成")
    # 生成bug周统计文件
    statisticsData2Week(projectId)
    Log.info(f"projectId : {projectId} Bug周统计文件 生成完成")
    init_finishTime = time.time()
    Log.info(f"projectId : {projectId} init datas is finished, used {round(init_finishTime-init_startTime, 2)} seconds")